<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useThemeStore } from '../stores/themeStore'
import { ElMessage } from 'element-plus'

const route = useRoute()
const themeStore = useThemeStore()

// 标签页控制
const activeTab = ref('theme')

// API调试相关
const apiUrl = ref('')
const requestMethod = ref('GET')
const requestData = ref('{\n  "key": "value"\n}')
const responseData = ref('')
const isLoading = ref(false)
const responseStatus = ref('')
const responseTime = ref(0)
const showResponse = ref(false)

// 发送API请求
const sendApiRequest = async () => {
  if (!apiUrl.value) {
    ElMessage.error('请输入API地址')
    return
  }

  isLoading.value = true
  showResponse.value = true
  responseData.value = ''
  responseStatus.value = ''
  
  const startTime = new Date().getTime()
  
  try {
    const options = {
      method: requestMethod.value,
      headers: {
        'Content-Type': 'application/json'
      }
    }
    
    // 如果是POST请求，添加请求体
    if (requestMethod.value === 'POST') {
      try {
        options.body = requestData.value ? JSON.stringify(JSON.parse(requestData.value)) : null
      } catch (e) {
        isLoading.value = false
        responseStatus.value = '错误'
        responseData.value = '请求数据JSON格式错误：' + e.message
        responseTime.value = 0
        return
      }
    }
    
    const response = await fetch(apiUrl.value, options)
    const endTime = new Date().getTime()
    responseTime.value = endTime - startTime
    
    try {
      // 尝试解析为JSON
      const data = await response.json()
      responseData.value = JSON.stringify(data, null, 2)
    } catch (e) {
      // 不是JSON格式，直接显示文本
      const text = await response.text()
      responseData.value = text
    }
    
    responseStatus.value = `${response.status} ${response.statusText}`
  } catch (error) {
    responseData.value = `请求错误：${error.message}`
    responseStatus.value = '错误'
  } finally {
    isLoading.value = false
  }
}

// 格式化JSON
const formatJson = () => {
  try {
    const formatted = JSON.stringify(JSON.parse(requestData.value), null, 2)
    requestData.value = formatted
  } catch (e) {
    ElMessage.error('JSON格式错误：' + e.message)
  }
}

// 清空表单
const clearForm = () => {
  apiUrl.value = ''
  requestMethod.value = 'GET'
  requestData.value = '{\n  "key": "value"\n}'
  responseData.value = ''
  showResponse.value = false
}

// 初始化主题
onMounted(() => {
  themeStore.initTheme()
  
  // 如果路由中有tab参数，则切换到对应标签
  if (route.query.tab) {
    activeTab.value = route.query.tab
  }
})
</script>

<template>
  <div class="setting-container">
    <div class="page-header bg-white p-4 rounded-lg shadow-sm mb-4">
      <h1 class="text-xl font-bold text-gray-800">系统设置</h1>
      <p class="text-gray-500 mt-1">自定义系统外观和行为</p>
    </div>

    <div class="content-container bg-white rounded-lg shadow-sm p-4">
      <!-- 设置标签页 -->
      <el-tabs v-model="activeTab" class="setting-tabs">
        <el-tab-pane label="主题设置" name="theme">
          <div class="theme-setting-container">
            <h2 class="text-lg font-medium mb-4">选择系统主题色</h2>
            
            <div class="theme-options grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              <div 
                v-for="theme in themeStore.themes" 
                :key="theme.id"
                class="theme-option overflow-hidden border rounded-lg cursor-pointer transition-all duration-300 hover:shadow-md transform hover:-translate-y-1"
                :class="{ 'theme-selected': themeStore.currentTheme === theme.id }"
                @click="themeStore.setTheme(theme.id)"
              >
                <!-- 主题预览头部 -->
                <div 
                  class="theme-preview-header h-24 p-3 flex flex-col justify-between"
                  :style="{ 
                    background: theme.gradient,
                    color: theme.textPrimary
                  }"
                >
                  <div class="flex justify-between items-center">
                    <span class="theme-name text-sm font-medium">{{ theme.name }}</span>
                    <div 
                      class="check-circle w-5 h-5 rounded-full flex items-center justify-center text-white transition-opacity"
                      :class="{ 'opacity-0': themeStore.currentTheme !== theme.id }"
                      :style="{ backgroundColor: theme.primary }"
                    >
                      <el-icon><Check /></el-icon>
                    </div>
                  </div>
                  
                  <div class="flex flex-wrap gap-1 mt-2">
                    <div 
                      class="color-dot w-5 h-5 rounded-full" 
                      :style="{ backgroundColor: theme.primary }"
                      :title="'主色: ' + theme.primary"
                    ></div>
                    <div 
                      class="color-dot w-5 h-5 rounded-full" 
                      :style="{ backgroundColor: theme.secondary }"
                      :title="'次色: ' + theme.secondary"
                    ></div>
                    <div 
                      class="color-dot w-5 h-5 rounded-full border" 
                      :style="{ 
                        backgroundColor: theme.cardBackground,
                        borderColor: theme.borderColor
                      }"
                      :title="'背景色: ' + theme.cardBackground"
                    ></div>
                  </div>
                </div>
                
                <!-- 主题预览内容 -->
                <div 
                  class="theme-preview-content p-3"
                  :style="{ 
                    backgroundColor: theme.cardBackground,
                    color: theme.textPrimary,
                    borderTop: `1px solid ${theme.borderColor}`
                  }"
                >
                  <div class="theme-preview-item">
                    <div class="text-xs font-medium mb-2" :style="{ color: theme.textSecondary }">界面预览</div>
                    
                    <div class="flex gap-2">
                      <!-- 模拟按钮 -->
                      <div 
                        class="h-7 flex-1 rounded-md flex items-center justify-center text-white text-xs" 
                        :style="{ backgroundColor: theme.primary }"
                      >
                        主按钮
                      </div>
                      <!-- 模拟标签 -->
                      <div 
                        class="h-7 px-2 rounded-md flex items-center justify-center text-white text-xs" 
                        :style="{ backgroundColor: theme.secondary }"
                      >
                        标签
                      </div>
                    </div>
                    
                    <!-- 模拟表格/列表 -->
                    <div class="mt-2 border rounded-md overflow-hidden text-xs" :style="{ borderColor: theme.borderColor }">
                      <div class="p-2 font-medium" :style="{ borderBottom: `1px solid ${theme.borderColor}` }">标题文本</div>
                      <div class="p-2" :style="{ color: theme.textSecondary }">描述内容</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="mt-6 p-4 bg-gray-50 rounded-lg">
              <h3 class="font-medium mb-2">主题设置提示</h3>
              <p class="text-gray-600 text-sm">选择一个适合你的主题颜色，系统会立即应用并保存你的偏好。主题色会影响整个系统的视觉风格，包括背景、按钮、链接和界面元素等。</p>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="接口调试" name="api">
          <div class="api-debug-container">
            <div class="mb-4">
              <h2 class="text-lg font-medium mb-4">API接口调试</h2>
              <p class="text-sm text-gray-500 mb-6">在此处测试API接口，支持GET和POST请求方式</p>
            </div>
            
            <el-card class="mb-6">
              <div class="request-form">
                <!-- API地址输入 -->
                <div class="mb-4">
                  <div class="flex items-center mb-2">
                    <el-icon class="mr-1 text-primary"><Link /></el-icon>
                    <span class="font-medium">请求地址</span>
                  </div>
                  <el-input 
                    v-model="apiUrl" 
                    placeholder="请输入API地址，例如：https://example.com/api/data" 
                    clearable
                  />
                </div>
                
                <!-- 请求方法选择 -->
                <div class="mb-4">
                  <div class="flex items-center mb-2">
                    <el-icon class="mr-1 text-primary"><Operation /></el-icon>
                    <span class="font-medium">请求方法</span>
                  </div>
                  <el-radio-group v-model="requestMethod" class="mb-2">
                    <el-radio-button label="GET">GET</el-radio-button>
                    <el-radio-button label="POST">POST</el-radio-button>
                  </el-radio-group>
                  <div class="text-xs text-gray-500">
                    <template v-if="requestMethod === 'GET'">
                      GET请求参数应当拼接在URL中，例如：https://example.com/api/data?id=1&name=test
                    </template>
                    <template v-else>
                      POST请求将以JSON格式发送数据
                    </template>
                  </div>
                </div>
                
                <!-- POST请求参数 -->
                <div v-if="requestMethod === 'POST'" class="mb-4">
                  <div class="flex items-center mb-2">
                    <el-icon class="mr-1 text-primary"><DocumentAdd /></el-icon>
                    <span class="font-medium">请求数据 (JSON格式)</span>
                  </div>
                  <el-input 
                    v-model="requestData"
                    type="textarea"
                    rows="5"
                    placeholder="请输入JSON格式的请求数据"
                    class="font-mono text-sm"
                  />
                  <div class="flex justify-end mt-2">
                    <el-button size="small" @click="formatJson">格式化</el-button>
                  </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="flex gap-2">
                  <el-button type="primary" @click="sendApiRequest" :loading="isLoading">
                    <el-icon class="mr-1"><Position /></el-icon>
                    发送请求
                  </el-button>
                  <el-button @click="clearForm">
                    <el-icon class="mr-1"><Delete /></el-icon>
                    清空
                  </el-button>
                </div>
              </div>
            </el-card>
            
            <!-- 响应结果 -->
            <el-card v-if="showResponse" class="response-container">
              <template #header>
                <div class="flex justify-between items-center">
                  <div class="flex items-center gap-2">
                    <el-icon class="text-primary"><DataAnalysis /></el-icon>
                    <span class="font-medium">响应结果</span>
                  </div>
                  <div class="flex items-center">
                    <el-tag v-if="responseStatus" size="small" :type="responseStatus.startsWith('2') ? 'success' : 'danger'">
                      {{ responseStatus }}
                    </el-tag>
                    <span v-if="responseTime" class="ml-2 text-sm text-gray-500">
                      {{ responseTime }}ms
                    </span>
                  </div>
                </div>
              </template>
              
              <div v-if="isLoading" class="py-10 flex flex-col items-center justify-center">
                <el-icon class="text-3xl animate-spin text-primary"><Loading /></el-icon>
                <span class="mt-2 text-sm text-gray-500">请求中...</span>
              </div>
              
              <div v-else>
                <el-input
                  v-model="responseData"
                  type="textarea"
                  rows="10"
                  readonly
                  class="font-mono text-sm"
                />
              </div>
            </el-card>
            
            <div class="mt-6 p-4 bg-gray-50 rounded-lg">
              <h3 class="font-medium mb-2">接口调试说明</h3>
              <p class="text-gray-600 text-sm mb-2">本工具仅用于开发和测试阶段的接口调试，请勿用于生产环境。</p>
              <ul class="text-gray-600 text-sm list-disc pl-5">
                <li>GET请求：参数需要在URL中以查询字符串形式提供</li>
                <li>POST请求：参数需要以JSON格式在请求数据区域提供</li>
                <li>跨域请求可能受到浏览器安全策略限制</li>
              </ul>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="系统参数" name="system">
          <div class="p-4">
            <p class="text-gray-500">更多系统参数设置正在开发中...</p>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="其他设置" name="other">
          <div class="p-4">
            <p class="text-gray-500">其他设置选项正在开发中...</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.setting-container {
  min-height: 100%;
}

.theme-option {
  border-width: 2px;
  transition: all 0.3s ease;
}

.theme-selected {
  box-shadow: 0 0 0 2px var(--el-color-primary);
  border-color: var(--el-color-primary);
}

.check-circle {
  transition: opacity 0.3s ease;
}

.color-dot {
  transition: transform 0.2s ease;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.color-dot:hover {
  transform: scale(1.2);
}

/* API调试样式 */
.api-debug-container {
  max-width: 1000px;
}

.font-mono {
  font-family: Monaco, Consolas, "Courier New", monospace;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style> 